package com.corpgovernment.organization.convert;

import cn.hutool.core.util.StrUtil;
import com.corpgovernment.api.applytrip.enums.ApplyTripEmployeeEnum;
import com.corpgovernment.api.applytrip.soa.response.TripPersonEffectResponse;
import com.corpgovernment.api.costcenter.model.CostCenter;
import com.corpgovernment.api.organization.bo.PassengerBO;
import com.corpgovernment.api.organization.model.passenger.CardVo;
import com.corpgovernment.api.organization.model.passenger.MobilePhoneVo;
import com.corpgovernment.api.organization.model.passenger.PassengerVo;
import com.corpgovernment.api.organization.model.user.NameInfoBo;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.organization.constant.PassengerConst;
import com.corpgovernment.organization.entity.db.*;
import com.corpgovernment.organization.enumm.CardCodeEnum;
import com.corpgovernment.organization.enumm.ProductTypeEnum;
import com.corpgovernment.organization.util.CardTypeSwitchUtil;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class PassengerConvert {
	@Autowired
	private OrganizationApollo organizationApollo;

	/**
	 * 根据出差申请单获取出行人
	 *
	 * @param personList
	 * @return
	 */
	public List<PassengerVo> convertFromTripPerson(List<TripPersonEffectResponse> personList) {
		return personList.stream().map(e -> {
			PassengerVo passenger = new PassengerVo();

			if (e.getEmpStatus() == 1) {
				passenger.setUid(e.getUid());
			} else {
				passenger.setNoEmployeeId(e.getUid());
			}
			passenger.setName(e.getPersonName());
			passenger.setOrgId(e.getOrgId());
			passenger.setProjectCode(e.getProjectCode());
			passenger.setProjectName(e.getProjectName());
			passenger.setNoSelectProjectDesc(e.getNoSelectProjectDesc());
			CostCenter costCenter = new CostCenter();
			costCenter.setUid(e.getUid());
			costCenter.setCostCenterCode(e.getCostCenterCode());
			costCenter.setCostCenterName(e.getCostCenterDesc());

			passenger.setCostCenter(costCenter);
			return passenger;
		}).collect(Collectors.toList());
	}

	/**
	 * 封装手机信息
	 *
	 * @param mobilePhone
	 * @return
	 */
	private MobilePhoneVo convertMobilePhone(String mobilePhone) {
		MobilePhoneVo mobilePhoneVo = new MobilePhoneVo();
		if (StringUtils.isNotBlank(mobilePhone)) {
			String[] s = mobilePhone.split(" ");
			String countryCode = "+86";
			String phone = "";
			if (s.length == 2) {
				countryCode = s[0];
				phone = s[1];
			} else {
				phone = s[0];
			}
			mobilePhoneVo.setCountryCode(countryCode);
			mobilePhoneVo.setValue(phone);
		}
		return mobilePhoneVo;
	}

	/**
	 * 封装证件信息
	 *
	 * @param cards
	 * @param site
	 * @return
	 */
	private List<CardVo> convertCardInfo(List<MbOrgUserIdcard> cards, String site) {
		if (CollectionUtils.isEmpty(cards)) {
			return new ArrayList<>();
		}
		List<CardVo> cardVoList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(cards)) {
			for (MbOrgUserIdcard card : cards) {
				// 过滤掉学生证
				if (CardCodeEnum.STUDENT_CARD.getCode().equals(card.getCardType().toString())) {
					continue;
				}
				CardVo cardVo = new CardVo();
				cardVo.setValue(card.getCardNo());
				cardVo.setType(card.getCardType());
				Date timeLimit = card.getTimeLimit();
				// 证件是否有效
				if (timeLimit != null) {
					cardVo.setIsValid(timeLimit.after(new Date()));
				} else {
					cardVo.setIsValid(false);
				}
				cardVo.setValidity(timeLimit);
				cardVo.setName(CardTypeSwitchUtil.getNameById(card.getCardType()));
				cardVo.setPlaceOfIssue(card.getPlaceOfIssue());

				cardVoList.add(cardVo);
			}
		}
		// 根据site判断产线，封装默认卡片信息
		// 火车票产线
		if (Objects.equals(site, ProductTypeEnum.TRAIN.getCode())) {
			for (int i = 0; i < cardVoList.size(); i++) {
				Integer type = cardVoList.get(i).getType();
				if (Objects.equals(type, Integer.valueOf(CardCodeEnum.ID_CARD.getCode()))) {
					CardVo remove = cardVoList.remove(i);
					cardVoList.add(remove);
				}
			}
		}
		// 机票产线 优先放身份证，其次是护照，其他身份信息不管排序
		if (Objects.equals(site, ProductTypeEnum.FLIGHT.getCode())) {
			Integer idCard = null;
			Integer passport = null;
			for (int i = 0; i < cardVoList.size(); i++) {
				if (cardVoList.get(i).getType().toString().equals(CardCodeEnum.ID_CARD.getCode())) {
					idCard = i;
				}
				if (cardVoList.get(i).getType().toString().equals(CardCodeEnum.PASSPROT.getCode())) {
					passport = i;
				}
			}
			if (idCard != null && passport != null) {
				Collections.swap(cardVoList, idCard, 0);
				Collections.swap(cardVoList, passport, 1);
			}
			if (idCard != null && passport == null) {
				Collections.swap(cardVoList, idCard, 0);
			}
			if (idCard == null && passport != null) {
				Collections.swap(cardVoList, passport, 0);
			}
		}
		return cardVoList;
	}

	/**
	 * 转换员工信息
	 *
	 * @param employeeInfo
	 * @param mbOrgInfo
	 * @param cardList
	 * @param site
	 * @return
	 */
	public PassengerVo convertFromEmployee(MbOrgEmployeeInfo employeeInfo, MbOrgInfo mbOrgInfo, List<MbOrgUserIdcard> cardList, String site) {
		// 是否读取nameInfo的数据,T:读取  F:不读取
		boolean nameInfoReadSwitch = "T".equalsIgnoreCase(organizationApollo.getNameInfoReadSwitch());
		PassengerVo passengerVo = new PassengerVo();
		if(nameInfoReadSwitch && StrUtil.isNotBlank(employeeInfo.getNameInfo())){
			NameInfoBo nameInfoBo = JsonUtils.parse(employeeInfo.getNameInfo(), NameInfoBo.class);
			passengerVo.setSurname(nameInfoBo.getSurname());
			passengerVo.setGivenname(nameInfoBo.getGivenname());
			passengerVo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nameInfoBo.getSurname(),nameInfoBo.getGivenname()));
			passengerVo.setFullName(nameInfoBo.getFullName());
			passengerVo.setNationality(nameInfoBo.getNationality());
		}else{
			passengerVo.setSurname(employeeInfo.getLastEnName());
			passengerVo.setGivenname(employeeInfo.getFirstEnName());
			passengerVo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(employeeInfo.getLastEnName(),employeeInfo.getFirstEnName()));
			passengerVo.setFullName(employeeInfo.getName());
			passengerVo.setNationality(employeeInfo.getNationality());
		}
		passengerVo.setUid(employeeInfo.getUid());
		passengerVo.setOrgId(employeeInfo.getOrgId());
		String eName = "";
		if (StringUtils.isNotBlank(employeeInfo.getFirstEnName())
				|| StringUtils.isNotBlank(employeeInfo.getMidEnName()) || StringUtils.isNotBlank(employeeInfo.getLastEnName())) {
			eName = (StringUtils.isNotBlank(employeeInfo.getFirstEnName()) ? employeeInfo.getFirstEnName() : "")
					+ (StringUtils.isNotBlank(employeeInfo.getMidEnName()) ? employeeInfo.getMidEnName() : "")
					+ "/" + (StringUtils.isNotBlank(employeeInfo.getLastEnName()) ? employeeInfo.getLastEnName() : "");
		}
		passengerVo.setPassport(eName);
		if (mbOrgInfo != null) {
			passengerVo.setDep(mbOrgInfo.getName());
			passengerVo.setOrgId(mbOrgInfo.getOrgId());
		}
		// 手机号切割出国家码和手机号
		MobilePhoneVo mobilePhoneVo = this.convertMobilePhone(employeeInfo.getMobilePhone());
		passengerVo.setTel(mobilePhoneVo);
		passengerVo.setCorp(true);
		passengerVo.setChildren(false);
		Date birthday = employeeInfo.getBirthday();
		if (birthday != null) {
			LocalDateTime localDateTime = LocalDateTime.ofInstant(birthday.toInstant(), ZoneId.systemDefault());
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			String format = dtf.format(localDateTime);
			PassengerVo.Birth birth = new PassengerVo.Birth();
			birth.setValue(format);
			passengerVo.setBirth(birth);
			//年龄判断：12岁以下
			if (StringUtils.isNotBlank(format)){
				LocalDate birthLocalDate = LocalDate.parse(format, dtf);
				LocalDate nowLocalDate = LocalDate.now();
				Period period = Period.between(birthLocalDate, nowLocalDate);
				int years = period.getYears();
				if (years < PassengerConst.CHILDREN_AGE_LIMIT) {
					passengerVo.setChildren(true);
					passengerVo.setChildrenForbidText(PassengerConst.CHILDREN_FORBID_TEXT);
				}
			}
		}
		String gender = employeeInfo.getGender();
		passengerVo.setGender(gender);
		passengerVo.setShowPass(true);
		passengerVo.setName(employeeInfo.getName());
		passengerVo.setMail(employeeInfo.getEmail());
		passengerVo.setEmployeeType(employeeInfo.getEmployeeType());
		passengerVo.setEmployeeDesc(ApplyTripEmployeeEnum.getNameByCode(employeeInfo.getEmployeeType()));
		List<CardVo> cardVoList = this.convertCardInfo(cardList, site);
		passengerVo.setSource(cardVoList);
		return passengerVo;
	}

	/**
	 * 转换非员工信息
	 *
	 * @param nonEmployeeInfo
	 * @param cardList
	 * @param site
	 * @return
	 */
	public PassengerVo convertFromNonEmployee(MbOrgNonEmployeeInfo nonEmployeeInfo, List<MbOrgUserIdcard> cardList, String site) {
		// 是否读取nameInfo的数据,T:读取  F:不读取
		boolean nameInfoReadSwitch = "T".equalsIgnoreCase(organizationApollo.getNameInfoReadSwitch());
		PassengerVo passengerVo = new PassengerVo();
		if(nameInfoReadSwitch && StrUtil.isNotBlank(nonEmployeeInfo.getNameInfo())){
			NameInfoBo nameInfoBo = JsonUtils.parse(nonEmployeeInfo.getNameInfo(), NameInfoBo.class);
			passengerVo.setSurname(nameInfoBo.getSurname());
			passengerVo.setGivenname(nameInfoBo.getGivenname());
			passengerVo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nameInfoBo.getSurname(),nameInfoBo.getGivenname()));
			passengerVo.setFullName(nameInfoBo.getFullName());
			passengerVo.setNationality(nameInfoBo.getNationality());
		}else{
			passengerVo.setSurname(nonEmployeeInfo.getLastEnName());
			passengerVo.setGivenname(nonEmployeeInfo.getFirstEnName());
			passengerVo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nonEmployeeInfo.getLastEnName(),nonEmployeeInfo.getFirstEnName()));
			passengerVo.setFullName(nonEmployeeInfo.getName());
			passengerVo.setNationality(nonEmployeeInfo.getNationality());
		}
		passengerVo.setNoEmployeeId(nonEmployeeInfo.getId().toString());
		passengerVo.setName(nonEmployeeInfo.getName());
		String eName = "";
		if (StringUtils.isNotBlank(nonEmployeeInfo.getFirstEnName())
				|| StringUtils.isNotBlank(nonEmployeeInfo.getMidEnName()) || StringUtils.isNotBlank(nonEmployeeInfo.getLastEnName())) {
			eName = (StringUtils.isNotBlank(nonEmployeeInfo.getFirstEnName()) ? nonEmployeeInfo.getFirstEnName() : "")
					+ (StringUtils.isNotBlank(nonEmployeeInfo.getMidEnName()) ? nonEmployeeInfo.getMidEnName() : "")
					+ "/" + (StringUtils.isNotBlank(nonEmployeeInfo.getLastEnName()) ? nonEmployeeInfo.getLastEnName() : "");
		}
		passengerVo.setPassport(eName);
		// 手机号切割出国家码和手机号
		MobilePhoneVo mobilePhoneVo = this.convertMobilePhone(nonEmployeeInfo.getMobilePhone());
		passengerVo.setTel(mobilePhoneVo);
		passengerVo.setCorp(false);
		Date birthday = nonEmployeeInfo.getBirthday();
		if (birthday != null) {
			LocalDateTime localDateTime = LocalDateTime.ofInstant(birthday.toInstant(), ZoneId.systemDefault());
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			String format = dtf.format(localDateTime);
			PassengerVo.Birth birth = new PassengerVo.Birth();
			birth.setValue(format);
			passengerVo.setBirth(birth);
		}
		String gender = nonEmployeeInfo.getGender();
		passengerVo.setGender(gender);
		passengerVo.setShowPass(true);
		List<CardVo> cardVoList = this.convertCardInfo(cardList, site);
		passengerVo.setSource(cardVoList);
		passengerVo.setEmp("非员工");
		passengerVo.setMail(nonEmployeeInfo.getEmail());
		return passengerVo;
	}

	public List<PassengerVo> convertFromFreshPassenger(List<MbFreshPassenger> freshPassengerList, String defaultOrgId) {
		if (CollectionUtils.isEmpty(freshPassengerList)) {
			return new ArrayList<>();
		}
		return freshPassengerList.stream().map(e -> {
			PassengerVo passenger = new PassengerVo();
			passenger.setId(e.getId());
			String employeeUid = e.getEmployeeUid();
			passenger.setUid(employeeUid);
			if (e.getNonEmployeeUid() != null){
				passenger.setNoEmployeeId(String.valueOf(e.getNonEmployeeUid()));
			}
			if (StringUtils.isBlank(e.getOrgId())) {
				// 非员工设置
				passenger.setOrgId(defaultOrgId);
			} else {
				passenger.setOrgId(e.getOrgId());
			}
			return passenger;
		}).collect(Collectors.toList());
	}

	public List<PassengerBO> convertFromVO(List<PassengerVo> plist) {
		if (CollectionUtils.isEmpty(plist)) {
			return new ArrayList<>();
		}
		return JsonUtils.parseArray(JsonUtils.toJsonString(plist), PassengerBO.class);
	}
}
